package com.example.gulimall.common.config.mobile;

import com.example.gulimall.common.enums.ServiceCodeEnum;
import com.example.gulimall.common.exceptions.ApiException;
import com.example.gulimall.common.perporties.SecurityProperties;
import com.example.gulimall.common.utils.ObjectMapperKit;
import com.example.gulimall.common.utils.WrappedHttpServletRequest;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

/**
 * 短信登录过滤器
 *
 * @author jiguodong
 * @since 1.0
 */
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    private String mobileParameter;

    public SmsCodeAuthenticationFilter(SecurityProperties securityProperties) {
        super(new AntPathRequestMatcher(securityProperties.getLoginByMobileUri(), "POST"));
        this.mobileParameter = securityProperties.getLoginByMobileParameterName();
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        WrappedHttpServletRequest requestWrapper = new WrappedHttpServletRequest(request);
        if (!"POST".equalsIgnoreCase(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String mobile = obtainMobile(requestWrapper);

        if (mobile == null) {
            mobile = "";
        }

        mobile = mobile.trim();

        SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);

        setDetails(requestWrapper, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected String obtainMobile(HttpServletRequest request) {
        String mobile = null;
        if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)
                || request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
            try (InputStream is = request.getInputStream()) {
                HashMap params = ObjectMapperKit.toObject(is, HashMap.class);
                mobile = (String) params.get(mobileParameter);
            } catch (IOException e) {
                logger.error("获取验证码参数异常", e);
                throw new ApiException(ServiceCodeEnum.PARAM_ERROR);
            }
        } else {
            mobile = request.getParameter(mobileParameter);
        }
        return mobile;
    }

    protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}